import { useDocumentStore } from '@/common/store';
import { FieldProps } from '@rjsf/utils';
import { Flex, Select } from 'antd';

function findChild(parent, options) {
  if (parent.children) {
    for (const child of parent.children) {
      if (child.children) {
        findChild(child, options);
      } else {
        options.push(child);
      }
    }
  }
  if (parent.details) {
    for (const detail of parent.details) {
      if (detail.children) {
        findChild(detail, options);
      } else {
        options.push(detail);
      }
    }
  }
}

export const SolverConfigField = ({
  schema,
  idSchema,
  uiSchema,
  formData,
  disabled,
  onChange,
}: FieldProps<number>) => {
  const layout2 = uiSchema['ui:layout'] ?? [1, 1];
  const label = uiSchema?.['ui:options']?.label ?? true;

  // 根据JsonPath，从database的分析参数 中获取对应的数据，并用列表显示出来让用户选择
  const { databaseInfo } = useDocumentStore();
  const solverConfig = databaseInfo.find(
    (value) => value.type === 'SolverConfig',
  );

  const paths = schema['JsonPath']?.split('.') ?? [];
  let condition;
  for (const path of paths) {
    const childrenOrDetails = solverConfig?.children ?? solverConfig?.details;
    condition = childrenOrDetails?.find((value) => {
      return value.type === path;
    });
  }
  let options = [];
  // 数据可能有多层，取最后一层的child
  if (condition) {
    findChild(condition, options);
  }
  options = options ?? [];

  return (
    <Flex
      style={{ gap: 4 }}
      className='items-center'>
      <Flex
        style={{ flex: layout2[0], gap: 10 }}
        className='items-center'>
        <span
          style={{ flex: 1 }}
          className='fs'>
          {label ? schema.title : ''}
        </span>
      </Flex>
      <Flex
        style={{
          width: 0,
          flex: layout2[1],
          gap: 5,
          overflow: 'hidden',
          fontSize: 12,
        }}>
        <Select
          style={{ width: '100%' }}
          styles={{ popup: { root: { borderRadius: '4px' } } }}
          placeholder='请选择'
          value={formData}
          disabled={disabled ? disabled : uiSchema['ui:disabled']}
          onChange={(value) => onChange(value, undefined, idSchema.$id)}>
          {options?.map((item, index) => (
            <Select.Option
              key={index}
              style={{ borderRadius: 'var(--item-border-radius) !important' }}
              disabled={item.disabled}
              value={item.id}
              label={item.name}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      </Flex>
    </Flex>
  );
};
